<template>
<div class="roleManage">
  <y-table
    border
    :getDataWay="{
      data: tableData
    }"
    :columns="columns"
  >
    <template slot="button">
      <el-button type="primary" @click="() => addRole()">添加角色</el-button>
    </template>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="210">
      <template v-slot="scope">
        <div class="table-buttons">
          <el-button type="primary" size="mini" @click="editAuth(scope.row)">授权</el-button>
          <el-button type="primary" size="mini" @click="editRole(scope.row)">编辑</el-button>
          <el-popconfirm
            title="是否确认删除该角色？"
            @confirm="delRole(scope.row)">
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <y-form
    v-model="forms.formModel"
    :visible.sync="forms.showForm"
    :title="forms.formTypeTitle[forms.formsType]"
    destroy-on-close
    width="50%"
    :form-attrs="forms.formAttrs"
    :columns="forms.formColumns"
    @ensure="ensureModel">
  </y-form>
  <y-form
    v-model="authForms.formModel"
    :visible.sync="authForms.showForm"
    :title="(authForms.currentForm ? authForms.currentForm.roleName : '') + '授权'"
    destroy-on-close
    width="50%"
    @opened="initAuth"
    @close="hideAuthForm"
    force-inner-scroll
    v-loading="authLoading"
    :form-attrs="authForms.formAttrs"
    :columns="authForms.formColumns">
    <template slot="auth">
      <el-tree
        v-if="authForms.showAuthTree"
        ref="tree"
        :data="authTree"
        default-expand-all
        show-checkbox
        :default-checked-keys="defaultCheckedKeys"
        node-key="id"
        :props="{ label: 'menuName', children: 'children' }"></el-tree>
    </template>
    <div class="dialog-footer" slot="footer">
      <el-button @click="authForms.showForm=false">关闭</el-button>
      <el-button type="primary" @click="saveAuth">保存</el-button>
    </div>
  </y-form>
</div>
</template>

<script>
export default {
  name: "roleManage",
  data(){
    return{
      tableData: [],
      columns: [{
        label: "角色名",
        prop: "roleName"
      },{
        label: "备注",
        prop: "remarks"
      },{
        label: "创建时间",
        prop: "createTime",
        formatter(row){
          return (row.createTime || '').replace('T', ' ');
        }
      }],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加角色',
          'EDIT': '编辑角色'
        },
        formModel:{
          roleName: '',
          remarks: '',
          tenantCanUse: '0'
        },
        currentForm: null,
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            roleName: [{required: true, message: "请输入角色名", trigger: "blur"}],
          }
        },
        formColumns:[
          {
            label: "角色名称",
            prop: "roleName",
            comp:{
              compType: 'input',
              attrs:{
                clearable: true,
                maxlength: '30',
                showWordLimit: true
              }
            }
          },
          {
            label: "备注",
            prop: "remarks",
            comp:{
              compType: 'input',
              attrs:{
                type: 'textarea',
                maxlength: '100',
                showWordLimit: true
              }
            }
          },
          {
            label: "可以分配",
            prop: "tenantCanUse",
            comp:{
              compType: 'switch',
              attrs:{
                activeValue: '1',
                inactiveValue: '0'
              }
            }
          }
        ]
      },
      authForms:{
        formModel:{
          auth: []
        },
        currentForm: null,
        showForm: false,
        showAuthTree: false,
        formAttrs:{
          labelWidth: '100px'
        },
        formColumns:[
          {
            label: "授权",
            prop: "auth",
            template: true
          }
        ]
      },
      authLoading: false,
      authTree: [],
      defaultCheckedKeys: []
    }
  },
  async mounted(){
    await this.queryList();
    await this.$yAxios({
      url: this.$api.system.queryMenuTree
    }, info => {
      this.authTree = info;
    })
  },
  methods:{
    queryList(){
      this.$yAxios({
        url: this.$api.system.queryRoles,
        loading: true
      }, info => {
        this.tableData = info;
      });
    },
    resetForm(){
      Object.keys(this.forms.formModel).map(key => {
        this.forms.formModel[key] = this.forms.currentForm ? this.forms.currentForm[key] : '';
      })
    },
    resetAuthForm(){
      this.forms.formModel.auth = [];
    },
    addRole(row, type = 'ADD'){
      this.forms.formsType = 'ADD';
      this.forms.currentForm = null;
      this.resetForm();
      this.forms.showForm = true;
    },
    editRole(row){
      this.forms.formsType = 'EDIT';
      this.forms.currentForm = row;
      this.resetForm();
      this.forms.showForm = true;
    },
    editAuth(row){
      this.authForms.currentForm = row;
      //TODO
      this.defaultCheckedKeys = [];
      this.resetAuthForm();
      this.authForms.showForm = true;
    },
    delRole(row){
      this.$yAxios({
        url: this.$api.system.removeRole,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.queryList();
      })
    },
    ensureModel(form){
      let newForm;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
      }else{
        newForm = Object.assign({}, form);
      }
      this.$yAxios({
        url: this.$api.system.saveOrUpdateRole,
        data: newForm
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        newForm = info;
        switch (this.forms.formsType){
          case 'ADD':{
            this.tableData.push(newForm);
            break;
          }
          case 'EDIT':{
            Object.assign(this.forms.currentForm, newForm);
            break;
          }
        }
      })
    },
    hideAuthForm(){
      this.authForms.showForm = false;
      this.authForms.showAuthTree = false;
    },
    initAuth(){
      this.authForms.showAuthTree = false;
      this.$yAxios({
        url: this.$api.system.queryRoleMenuByRoleId,
        data:{
          id: this.authForms.currentForm.id
        },
        yLoading: 'authLoading'
      }, info => {
        //筛选出叶子节点
        this.defaultCheckedKeys = info.filter(menu => !info.some(m => menu.id === m.menuPid)).map(menu => menu.id);
        this.authForms.showAuthTree = true;
      })
    },
    clearAuth(){
      this.$refs['tree'].setCheckedKeys([]);
    },
    saveAuth(){
      //获取勾选以及半勾选的数据
      let checkedKeys = this.$refs['tree'].getCheckedKeys();
      let allKeys = new Set();
      checkedKeys.map(key => {
        allKeys.add(key);
        let tmpNode = this.$refs['tree'].getNode(key);
        while(!!(tmpNode.parent && tmpNode.parent.key)){
          tmpNode = tmpNode.parent;
          allKeys.add(tmpNode.data.id);
        }
      });
      this.$yAxios({
        url: this.$api.system.saveRoleMenuRelation,
        data:{
          menuIds: [...allKeys],
          roleId: this.authForms.currentForm.id
        }
      }, info => {
        this.authForms.showForm = false
        this.$message({
          type: 'success',
          message: '授权成功'
        });
      });
    }
  }
}
</script>

<style scoped lang="less">
.roleManage{
  margin-top: -20px;
}
</style>